﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Needle.Framework;
using Needle.Utils.Extensions;
using System.ComponentModel.Design;

namespace Needle.DevToolkit.Services
{
    public abstract class ServiceBase : IInitializable, IDisposable
    {

        private IServiceProvider _services;
        protected IServiceProvider Services
        {
            get { return _services; }
        }

        public ServiceBase(IServiceProvider serviceProvider)
        {
            if (serviceProvider == null)
                throw new ArgumentNullException("serviceProvider", "serviceProvider is null.");
            _services = serviceProvider;
        }

        ~ServiceBase()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected abstract Type[] ExposedServices { get; }

        protected virtual void Dispose(bool disposing)
        {
            IServiceContainer svcContainer = Services.GetService<IServiceContainer>();
            foreach (Type type in ExposedServices)
            {
                if (svcContainer.GetService(type) == this)
                    svcContainer.RemoveService(type);
            }
            _services = null;
        }


        public void Initialize()
        {
            IServiceContainer svcContainer = Services.GetService<IServiceContainer>();
            foreach (Type type in ExposedServices)
            {
                if (svcContainer.GetService(type) == this)
                    svcContainer.AddService(type, this);
            }
        }
    }
}
